package com.walleipt.ipt_tools.async;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 异步线程池【项目如需使用异步线程池时，强烈建议使用此封装类，除非自行确保不会调用header或者自行清除】
 * 
 * 注意：需要将该类托管到spring配置下，销毁线程池
 * @author Bisharp
 */
public class AsyncThreadPool {

	private static class PoolHolder {
		private static ExecutorService POOL = Executors.newFixedThreadPool(20);
	}
	
	private static ExecutorService getExecutorService() {
		return PoolHolder.POOL;
	}
	
	public static void execute(final AsyncCommand cmd) {
		getExecutorService().execute(new Runnable() {

			@Override
			public void run() {
				cmd.beforeExecute();
				cmd.command();
				cmd.beforeReturn();
			}
			
		});
		
	}
	
	public static <T> Future<T> submit(final AsyncTask<T> task) {
		return getExecutorService().submit(new Callable<T>() {

			@Override
			public T call() throws Exception {
				task.beforeExecute();
				T t = task.task();
				task.beforeReturn();
				return t;
			}
			
		});
	}
	
	/**
	 * 销毁线程池
	 */
	public static void destroy() {
		if (!PoolHolder.POOL.isShutdown()) {
			System.out.println("pool shutdown.....");
			PoolHolder.POOL.shutdown();
		}
	}
}
